/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

#include "se_defines.h"
#include "utils.h"

SE_GLOBALS()

const char* read_string(Input* input) {
  return input->read_string().c_str();
}

void memory_alloc(Input* input) {
  int size = input->read_int(); // Read the number of bytes to spray
  char* ptr = reinterpret_cast<char*>(malloc(size));
  memset(ptr, 0, size);
  input->read_bytes_n(reinterpret_cast<uint8_t*>(ptr), size);
}

void test_case(std::string content) {
  Input input(reinterpret_cast<uint8_t*>(content.data()), content.size());

  const char* str = nullptr;

  bool should_run = true;
  while (should_run) {
    switch (input.read_char()) {
      case 's':
        str = read_string(&input);
        if (strcmp(str, "admin") == 0) {
          // Do not allow admin
          return;
        }
        break;
      case 'h':
        memory_alloc(&input);
        break;
      case 'q':
        should_run = false;
        break;
    }
  }

  if (str != nullptr && strcmp(str, "admin") == 0) {
    SE_TARGET_STATE(true);
  }
}

int main(int argc, char* argv[]) {
  std::istream* input;
  std::ifstream file;
  if (argc < 2) {
    input = &std::cin; // No file name provided, read from stdin
  } else {
    file.open(argv[1]);
    if (!file) {
      std::cerr << "Could not open the file.\n";
      return 1;
    }
    input = &file; // File opened successfully, read from file
  }
  std::string content(
      (std::istreambuf_iterator<char>(*input)),
      std::istreambuf_iterator<char>());
  test_case(content);
  return 0;
}
